<?php

// +----------------------------------------------------------------------
// | Author: pp <124910168@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\controller;

use controller\BasicAdmin;
use app\admin\model\NodeModel;
use service\DataService;
use service\ToolsService;
use service\LogService;
use think\Db;
use Endroid\QrCode\QrCode;

class Domain extends BasicAdmin {

    /**
     * 指定当前数据表
     * @var string
     */
    public $aid;
    public $aids;
    public $domain;
    public $table = 'Domain';
    public $areaTreeTable = 'Area';
    public $tempTreeTable = 'Tmp';

    public function _initialize()
    {
        parent::_initialize();
        $this->domain = Db::name($this->table);
    }

    /**
     * 数据列表
     */
    public function index() {
        // 设置页面标题
        $this->title = '站点';
        // 获取到所有GET参数
        $get = $this->request->get();
        $map = [
            'is_deleted' => '0',
            // 'status' => 1,
            'zone_id' => ['in', $this->aids],
        ];
        $db = $this->domain->where($map)->order('sort desc,id asc');
        foreach (['title', 'domain','zone_id','admin_id'] as $key) {
            if (isset($get[$key]) && $get[$key] !== '') {
                if($key == 'zone_id'){
                    // $areas = $this->AR->order('area_id asc')->select();
                    // $aids = ToolsService::getArrSubIds($areas,$get[$key],'area_id','area_parent_id');//当前区域下地区Ids
                    $aids = _getAIDs($get[$key]);
                    $db->where($key, 'in', $aids);
                }elseif($key == 'admin_id'){
                    $uids = Db::connect(config('dbx.SU'))->name('SystemUser')->where('username', 'like', "%{$get[$key]}%")->column('id');
                    // halt($uids);
                    $db->where($key, 'in', $uids);
                }else{
                    $db->where($key, 'like', "%{$get[$key]}%");                 
                }
            }
        }
        // halt($db);

        // $adminList = Db::connect(config('dbx.SU'))->name('SystemUser')->where(['status' => 1, 'id' => ['neq', 1]])->select();
        // $this->assign('adminList', $adminList);
        
        $areaList = $this->_getAreaTrees('Area', ['area_open' => 1, 'area_id' => ['in', $this->aids]]);
        $this->assign('areaList', $areaList);
        // halt($areaList);
        $data = parent::_list($db, true, false);
        return $this->fetch('', $data);
    }

    //列表数据
    protected function _index_data_filter(&$data) {
        // halt($data);
        foreach ($data as &$vo) {
        }
    }
    public function sData($aid = 1){
        //获取统计数据
            // $areas = $this->AR->order('area_id asc')->select();
            // $aids = ToolsService::getArrSubIds($areas,$aid,'area_id','area_parent_id');//当前区域下地区Ids
            $aids = _getAIDs($aid);
                $map = [
                    'is_deleted' => '0',
                    'status' => 0,
                    'zone_id' => ['in', $aids],
                ];
            
            $data['total'] = $this->domain->where($map)->count();//总共站点数
            $data['totalUNum'] = $this->SU->where(['status' => 1, 'is_deleted' => '0'])->count();//总后台用户数

            //用户
            $managerMap = [
                'status' => 1,
                'is_deleted' => '0',
                'id' => ['neq', 1],
                'aid' => ['in', $aids],
                'authorize' => ['like', ["%2%","%4%","%6%","%8%"],'or'],
            ];
            $data['managerUNum'] = $this->SU->where($managerMap)->count();//主管用户数

            $serviceMap = [
                'status' => 1,
                'is_deleted' => '0',
                'id' => ['neq', 1],
                'aid' => ['in', $aids],
                'authorize' => ['like', ["%3%","%5%","%7%","%9%"],'or'],
            ];
            $data['serverUNum'] = $this->SU->where($serviceMap)->count();//服务商用户数
            
            $enterMap = [
                'status' => 1,
                'is_deleted' => '0',
                'id' => ['neq', 1],
                'aid' => ['in', $aids],
                'authorize' => ['like', ["%10%"]],
            ];
            $data['enterUNum'] = $this->SU->where($enterMap)->count();//企业用户数
            
            $dsMap = [
                'status' => 1,
                'is_deleted' => '0',
                'id' => ['neq', 1],
                'aid' => ['in', $aids],
                'authorize' => ['like', ["%11%"]],
            ];
            $data['dsUNum'] = $this->SU->where($dsMap)->count();//电商扶贫示范户用户数
            
            $hsMap = [
                'status' => 1,
                'is_deleted' => '0',
                'id' => ['neq', 1],
                'aid' => ['in', $aids],
                'authorize' => ['like', ["%12%"]],
            ];
            $data['jdUNum'] = $this->SU->where($hsMap)->count();//建档立卡扶贫示范户用户数

            //站点
            $areas1 = $this->AR->where(['area_deep' => 1])->column('area_id');
                $map1 = [
                    'is_deleted' => '0',
                    'status' => 0,
                    'zone_id' => ['in', $areas1],
                ];
            $data['state'] = $this->domain->where($map1)->count();//总共县级站点数

            $areas2 = $this->AR->where(['area_deep' => 2])->column('area_id');
                $map2 = [
                    'is_deleted' => '0',
                    'status' => 0,
                    'zone_id' => ['in', $areas2],
                ];
            $data['county'] = $this->domain->where($map2)->count();//总共县级站点数

            $areas3 = $this->AR->where(['area_deep' => 3])->column('area_id');
                $map3 = [
                    'is_deleted' => '0',
                    'status' => 0,
                    'zone_id' => ['in', $areas3],
                ];
            $data['town'] = $this->domain->where($map3)->count();//总共镇级站点数

            $areas4 = $this->AR->where(['area_deep' => 4])->column('area_id');
                $map4 = [
                    'is_deleted' => '0',
                    'status' => 0,
                    'zone_id' => ['in', $areas4],
                ];
            $data['village'] = $this->domain->where($map4)->count();//总共村级站点数

            // halt($data);
            return $data;
    }


    public function _getAdminUs(){
        $map = [
            'status' => 1,
            'id' => ['neq', 1],
            'is_deleted' => '0',
            'aid' => ['in', $this->aids],
            ];
        $adminList = Db::connect(config('dbx.SU'))->name('SystemUser')->where($map)->column('id,id as kid,username');
        $admin = [['value' => 1, 'label' => 'pp']];
        // foreach ($adminList as $k => $v) {
        //     $admin[$k]['value'] = $v['kid'];
        //     $admin[$k]['label'] = $v['username'];
        // }
        // halt($admin);
        return $admin;
    }

    /**
     * 用户待审核列表
     */
    public function status() {
        // 设置页面标题
        $this->title = '站点管理';
        // 获取到所有GET参数
        $get = $this->request->get();
        $map = [
            'is_deleted' => '0',
            'status' => 0
        ];
        // 实例Query对象
        $db = $this->domain->where($map);
        // 应用搜索条件
        foreach (['username', 'phone'] as $key) {
            if (isset($get[$key]) && $get[$key] !== '') {
                $db->where($key, 'like', "%{$get[$key]}%");
            }
        }

        $data = parent::_list($db, true, false);

        if(!empty($data['list'])){
            foreach ($data['list'] as $key => $list) {
                $sc_name='';
                $sc_id=array();
                if(!empty($list['sc_id'])){
                    $sc_id=explode(",",trim($list['sc_id'],','));
                }
                if(!empty($sc_id)){
                    foreach($sc_id as $k=>$v){
                        $sc_name.=Db::name('store_class')->where(array('sc_id'=>$v))->value('sc_name').',';
                    }
                }
                $data['list'][$key]['storeclass'] = trim($sc_name,',');
            }
        }
        // 获取商品分类
        return $this->fetch('index', $data);
    }

    /**
     * 授权管理
     * @return array|string
     */
    public function auth()
    {
        return $this->_form($this->table, 'auth');
    }

    /**
     * 授权管理表单数据默认处理
     * @param array $data
     */
    public function _auth_form_filter(&$data)
    {
        if ($this->request->isPost()) {
            $ret = $this->domain->update($data);
            // $res = Db::name('DomainStaff')->where('create_by',$data['id'])->update(['authorize'=>$data['authorize']]);
            LogService::write('系统设置', '站点授权修改成功');
            $ret!== false ? $this->success('恭喜，保存成功哦！!', '') : $this->error('保存失败，请稍候再试！');
        }
    }

    /**
     * 用户添加
     */
    public function add()
    {        
        return $this->_form($this->table, 'form');
    }

    /**
     * 用户编辑
     */
    public function edit() {
        return $this->_form($this->table, 'form');
    }

    /**
     * 表单数据默认处理
     * @param array $data
     */
    public function _form_filter(&$data) {
        if ($this->request->isPost()) {
            // halt($data);
            if (isset($data['authorize']) && is_array($data['authorize'])) {
                $data['authorize'] = join(',', $data['authorize']);
            }

            //域名+地区去重判断
            $doMap = ['domain' => $data['domain']];
            $do2Map = ['admin_id' => $data['admin_id']];
            $do3Map = ['zone_id' => $data['zone_id'], 'is_deleted' => 0];
            if (isset($data['id'])) {
                $doMap['id'] = $do2Map['id'] = $do3Map['id'] = ['neq', $data['id']];
            }
             
            if(!$data['admin_id']){
                $this->error('请选择管理员');
            }
            if(!$data['zone_id']){
                $this->error('请选择地区');
            }
            if(!$data['temp_id']){
                $this->error('请选择模板');
            }

            $adminInfo = Db::connect(config('dbx.SU'))->name('SystemUser')->where(['id' => $data['admin_id']])->find();
            if($adminInfo['aid'] != $data['zone_id']){
                $this->error('管理员所属地区与当前站点地区不一致');
            }

            $domainInfo = Db::name('Domain')->where($do2Map)->find();
            if($domainInfo){
                $this->error('该用户已关联其它站点');
            }
            
            if ($this->domain->where($do3Map)->find()) {
                $this->error('该地区站点已经存在，请勿重复添加！');
            }
            
            if (isset($data['id'])) {
                // unset($data['username']);
                //生成二维码
                $qrcode = $this->_get_domain_qrcode($data['id']);
                DataService::save($this->table, ['id' => $data['id'], 'qrcode' => $qrcode]);
                LogService::write('系统设置', '站点修改成功');
            }else{
                // $data['create_by'] = session('user.id');
            }
            // halt($data);
        } else {
            $data['authorize'] = explode(',', isset($data['authorize']) ? $data['authorize'] : '');
            $areaList = $this->_getAreaTrees('Area', ['area_open' => 1, 'area_id' => ['in', $this->aids]]);
            $this->assign('areaList', $areaList);
            $map = [
                'status' => 1,
                'id' => ['neq', 1],
                'is_deleted' => '0',
                'aid' => ['in', $this->aids],
                ];
            $adminList = Db::connect(config('dbx.SU'))->name('SystemUser')->where($map)->select();
            $this->assign('adminList', $adminList);
            // $areaList = $this->_getAreaTrees();
            // $this->assign('areaList', $areaList);
            $tempList = $this->_getTempTrees();
            $this->assign('tempList', $tempList);
        }
    }

    public function _add_form_result($data){
        // halt($data);
        $domain_id = intval($data);
        $domainInfo = Db::name('Domain')->where($do2Map)->find();
        if($domain_id){
            $qrcode = $this->_get_domain_qrcode($domain_id);
            DataService::save($this->table, ['id' => $domain_id, 'qrcode' => $qrcode]);
            LogService::write('系统设置', '站点添加成功');
        }
    }

    /**
     * 生成二维码
     * $domain_id 站点id
     */
    protected function _get_domain_qrcode($domain_id){
        // $aid = Db::name('Domain')->where(['id' => $domain_id])->value('zone_id');
        $url = get_root_url().'/?d='.$domain_id;
        $save_path = '/static/domain/'.$domain_id.'/';
        $filename = $domain_id.'.png';
        // if(file_exists($save_path.$filename))return $save_path.$filename;
        if(file_exists($save_path.$filename)){
            unlink($save_path.$filename);
        }
        $qrCode = new QrCode();
        $qrCode->setText($url)
            ->setSize(300)
            ->setPadding(10)
            ->setErrorCorrection('high')
            ->setForegroundColor(array('r' => 0, 'g' => 0, 'b' => 0, 'a' => 0))
            ->setBackgroundColor(array('r' => 255, 'g' => 255, 'b' => 255, 'a' => 0))
            ->setImageType(\Endroid\QrCode\QrCode::IMAGE_TYPE_PNG);
        // 创建目录
        if(!is_dir(ROOT_PATH.'/static/domain/')) {
            @mkdir(ROOT_PATH.'/static/domain/', 0777);
        }
        if(!is_dir(ROOT_PATH.'/static/domain/'.$domain_id.'/')) {
            @mkdir(ROOT_PATH.'/static/domain/'.$domain_id.'/', 0777);
        }
        $qrCode->save(ROOT_PATH.$save_path.$filename);
        return $save_path.$filename;
    }

    /**
     * 删除数据
     */
    public function del() {
        if (in_array('1', explode(',', $this->request->post('id')))) {
            $this->error('系统超级账号禁止删除！');
        }
        if (DataService::update($this->table)) {
            LogService::write('系统设置', '站点删除成功');
            $this->success("数据删除成功！", '');
        }
        $this->error("数据删除失败，请稍候再试！");
    }

    /**
     * 数据禁用
     */
    public function forbid() {
        if (in_array('1', explode(',', $this->request->post('id')))) {
            $this->error('系统超级账号禁止操作！');
        }
        if (DataService::update($this->table)) {
            // if(Db::name($this->tableStaff)->where('create_by',input("post.id"))->update(array('status'=>0))){
            LogService::write('系统设置', '站点禁用成功');
                $this->success("数据禁用成功！", '');
            // }
        }
        $this->error("数据禁用失败，请稍候再试！");
    }

    /**
     * 数据启用
     */
    public function resume() {
        if (DataService::update($this->table)) {
            // if(Db::name($this->tableStaff)->where('create_by',input("post.id"))->update(array('status'=>1))){
            LogService::write('系统设置', '站点启用成功');
                $this->success("数据启用成功！", '');
            // }
        }
        $this->error("数据启用失败，请稍候再试！");
    }

    /**
     * 管理员推最新
     */
    public function is_recommoned(){
        $post=$this->request->post();
        if($post['is_recommoned']=='true'){
            return $this->domain->where(array('id'=>$post['id']))->update(array('is_recommoned'=>1));
        }else{
            return $this->domain->where(array('id'=>$post['id']))->update(array('is_recommoned'=>0));
        }
    }

}
